package com.example.Utils;

import cn.hutool.core.bean.BeanUtil;
import com.example.model.Admin;
import com.example.model.User;
import com.example.service.impl.UserServiceImpl;
import org.slf4j.Logger;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

public class AdminLoginInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;
    private static final Logger logger = LoggerUtils.getLogger(UserServiceImpl.class);

    public AdminLoginInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //获取token
        String token = request.getHeader("authorization");
        logger.info("来访的admin的token是：{}",token);
        //token不存在，拦截
        if (token == null){
            response.setStatus(401);
            return false;
        }
        //redis获取用户信息
        Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(token);
        map.forEach((k, v) -> {
            logger.info("key : " + k + " Value : " + v);

        });
        //用户是否存在
        //不存在，拦截，状态码：401 未授权
        if (map.isEmpty()){
            response.setStatus(401);
            return false;
        }
        Admin admin = BeanUtil.fillBeanWithMap(map, new Admin(), false);

        //存在，把用户放到ThreadLocal中
        UserHolder.saveAdmin(admin);
        //刷新token有效期
        stringRedisTemplate.expire(token,10, TimeUnit.MINUTES);
        //放行
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //移除用户
        UserHolder.removeAdmin();
    }

}
